/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.activity.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Maps;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.activity.entity.Activity;
import com.jeeplus.modules.activity.entity.ActivityEchartDataVo;
import com.jeeplus.modules.activity.entity.ActivityEchartDto;
import com.jeeplus.modules.activity.entity.ActivityEchartVo;
import com.jeeplus.modules.activity.entity.ActivityRecord;
import com.jeeplus.modules.oa.entity.OaNotifyRecord;
import com.jeeplus.modules.project.entity.BaseProjectInfo;
import com.jeeplus.modules.sys.entity.Dict;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.mysql.fabric.xmlrpc.base.Array;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.activity.dao.ActivityDao;
import com.jeeplus.modules.activity.dao.ActivityRecordDao;

/**
 * 活动管理Service
 * @author lw
 * @version 2018-01-14
 */
@Service
@Transactional(readOnly = true)
public class ActivityService extends CrudService<ActivityDao, Activity> {
	@Autowired
	private ActTaskService actTaskService;
	
	@Autowired
	private ActivityRecordDao activityRecordDao; 
	
	@Autowired
	private ActivityDao activityDao;
	public Activity get(String id) {
		return super.get(id);
	}
	
	public List<Activity> findList(Activity activity) {
		return super.findList(activity);
	}
	
	public Page<Activity> findPage(Page<Activity> page, Activity activity) {
		return super.findPage(page, activity);
	}
	
	@Transactional(readOnly = false)
	public void save(Activity activity) {
		/*super.save(activity);
		activityRecordDao.deleteByActId(activity.getId());
		List<ActivityRecord> activityRecordList = activity.getActivityRecordList();
		if(activityRecordList.size()>0) {
			activityRecordDao.insertBatch(activityRecordList);
		}*/
		   // 申请发起
		
			
			String title= "[活动申报]";
			if(StringUtils.isNoneBlank(activity.getActName())) {
				title += activity.getActName();
			}
				if (StringUtils.isBlank(activity.getId())){
					activity.preInsert();
					//填表日期，设置成当前的日期
					activity.setCreateDate(new Date());
					activityDao.insert(activity);
					activityRecordDao.deleteByActId(activity.getId());
					List<ActivityRecord> activityRecordList = activity.getActivityRecordList();
					if(activityRecordList.size()>0) {
						activityRecordDao.insertBatch(activityRecordList);
					}
					
					// 启动流程
					actTaskService.startProcess(ActUtils.PD_ACTIVITY_APPLY[0], ActUtils.PD_ACTIVITY_APPLY[1], activity.getId(), title);
					//更新状态 ，已经发起申请了
					activity.setProcessNode("2");
					
					try {
						//更改流程节点状态
						activityDao.updateProcessNode(activity);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				// 重新编辑申请		
				else{
					activity.preUpdate();
					activity.setProcessNode("2");
					activityDao.update(activity);
					activity.getAct().setComment(("yes".equals(activity.getAct().getFlag())?"[重申] ":"[销毁] ")+activity.getAct().getComment());
					
					// 完成流程任务
					Map<String, Object> vars = Maps.newHashMap();
					vars.put("pass", "yes".equals(activity.getAct().getFlag())? "1" : "0");
					actTaskService.complete(activity.getAct().getTaskId(), activity.getAct().getProcInsId(), activity.getAct().getComment(),title, vars);
					if("no".equals(activity.getAct().getFlag())){
						activity.setProcessNode("0");
						activityDao.update(activity);
					}
					

				}
	}
	
	@Transactional(readOnly = false)
	public void delete(Activity activity) {
		super.delete(activity);
	}
	
	public Activity getActRecordList(Activity activity) {
		if(activity.getId() != null  && !activity.getId().equals("")) {
			ActivityRecord record = new ActivityRecord();
			record.setActivity(activity);	
			activity.setActivityRecordList(activityRecordDao.findList(record));
		}
		
		return activity;
	}
	@Transactional
	public void approveSave(Activity activity) {
		// 设置意见
		activity.getAct().setComment(("yes".equals(activity.getAct().getFlag())?"[同意] ":"[驳回] ")+activity.getAct().getComment());
				
		activity.preUpdate();
				
				// 对不同环节的业务逻辑进行操作
				String taskDefKey = activity.getAct().getTaskDefKey();

				// 审核环节
				if ("dept-review".equals(taskDefKey)){
					activity.setDeptApproveAdvice(activity.getAct().getComment());
				}
				else if ("dept-leader-review".equals(taskDefKey)){
					activity.setDeptLeaderAdvice(activity.getAct().getComment());
				}
				
				else if ("sci-research-magt-review".equals(taskDefKey)){
					activity.setSciresearchDeptAdvice(activity.getAct().getComment());
				}
				else if ("big-boss-review".equals(taskDefKey)){
					activity.setBossLeaderAdvice(activity.getAct().getComment());
				}
				// 未知环节，直接返回
				else{
					return;
				}
				//更新数据
				activityDao.update(activity);
				
				// 提交流程任务
				Map<String, Object> vars = Maps.newHashMap();
				//最后一步如果同意，则更新项目信息状态
				if ("big-boss-review".equals(taskDefKey)){
					//vars.put("fin_pass", "yes".equals(activity.getAct().getFlag())? "1" : "0");
					if("yes".equals(activity.getAct().getFlag())){
					
						activity.setProcessNode("3");
						try {
							activityDao.updateProcessNode(activity);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				
				if(!"yes".equals(activity.getAct().getFlag())){
					activity.setProcessNode("1");
					try {
						activityDao.updateProcessNode(activity);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				vars.put("pass", "yes".equals(activity.getAct().getFlag())? "1" : "0");
				actTaskService.complete(activity.getAct().getTaskId(), activity.getAct().getProcInsId(), activity.getAct().getComment(), vars);

			}
	/**
	 * 保存附件
	 * @param activity
	 */
	@Transactional(readOnly = false)
	public void saveFilePath(Activity activity) {
		if(StringUtils.isNotBlank(activity.getFilePath())) {
			activityDao.updateFilePath(activity);
		}
	}
	/**
	 * Echart 数据
	 */
	public ActivityEchartVo echartView(String officeId) {
		List<ActivityEchartDataVo> echartDataVo = new ArrayList<ActivityEchartDataVo>();
		List<String> years = new ArrayList<String>();
		List<String> types = new ArrayList<String>();
		List<Dict> dictList = DictUtils.getDictList("activiti_event");
		List<ActivityEchartDto> selectYears = activityDao.selectYears();
		for (ActivityEchartDto activityEchartDto : selectYears) {
			years.add(activityEchartDto.getYears());
		}
		List<ActivityEchartDto> echartViewData;
		if (StringUtils.isEmpty(officeId)) {
			echartViewData = activityDao.echartViewAllData();
		} else {
			echartViewData = activityDao.echartViewData(officeId);	
		}
		//分类型： 	'外出调研', '学术交流', '出国访问', '学习深造', '接待'			
		for (Dict dict : dictList) {
			ActivityEchartDataVo echartData = new ActivityEchartDataVo(); //封装的echart数据对象格式 { name: '外出调研',type: 'bar',data: [30, 33, 39]},
			List<Integer> data = new ArrayList<Integer>();// data: [30, 33, 39]
			int num = 0;
			for(int i = 0; i<echartViewData.size() ;i++) {
				//判断类型相同
				if(dict.getValue().equals(echartViewData.get(i).getActivitiEvent())) {
					ActivityEchartDto activityEchartDto = echartViewData.get(i);
					//判断年份 （已经排序了）
					if(StringUtils.equals(years.get(num),activityEchartDto.getYears() )) {		// { name: '外出调研',type: 'bar',data: [30, 33, 39]},
						data.add( echartViewData.get(i).getTotal());
						num++;
					}else {
						int index = yearsCompare(num,years,activityEchartDto,data);
						num = index;
					}
				}
			}
			Integer[] arr = new Integer[data.size()];
			echartData.setName(dict.getLabel());
			echartData.setType("bar");
			echartData.setData(data.toArray(arr));
			echartDataVo.add(echartData);
			types.add(dict.getLabel());
		}
		ActivityEchartVo echartVo = new ActivityEchartVo();
		echartVo.setEchartDataVo(echartDataVo);
		echartVo.setTypes(types);
		echartVo.setYears(years);
		return echartVo;
	}

	public ActivityEchartVo echartAllView() {
		List<ActivityEchartDataVo> echartDataVo = new ArrayList<ActivityEchartDataVo>();
		List<String> years = new ArrayList<String>();
		List<String> types = new ArrayList<String>();
		//字典数据  
		List<Dict> dictList = DictUtils.getDictList("activiti_event");
		List<ActivityEchartDto> selectYears = activityDao.selectYears();
		for (ActivityEchartDto activityEchartDto : selectYears) {
			years.add(activityEchartDto.getYears());
		}
		List<ActivityEchartDto> echartViewData = activityDao.echartAllViewData();
		//分类型： 	'外出调研', '学术交流', '出国访问', '学习深造', '接待'			
		for (Dict dict : dictList) {
			ActivityEchartDataVo echartData = new ActivityEchartDataVo(); //封装的echart数据对象格式 { name: '外出调研',type: 'bar',data: [30, 33, 39]},
			List<Integer> data = new ArrayList<Integer>();// data: [30, 33, 39]
			//可能获取的数据，某个年份的数据没有，要在当前年份的数据输入0
			int num = 0;
			for(int i = 0; i<echartViewData.size() ;i++) {
				//判断类型相同
				if(dict.getValue().equals(echartViewData.get(i).getActivitiEvent())) {
					ActivityEchartDto activityEchartDto = echartViewData.get(i);
					
					//判断年份 （已经排序了）
					if(StringUtils.equals(years.get(num),activityEchartDto.getYears() )) {		// { name: '外出调研',type: 'bar',data: [30, 33, 39]},
						data.add( echartViewData.get(i).getTotal());
						num++;
					}else {
						int index = yearsCompare(num,years,activityEchartDto,data);
						num = index;
					}
				}
			}
			Integer[] arr = new Integer[data.size()];
			echartData.setName(dict.getLabel());
			echartData.setType("bar");
			echartData.setData(data.toArray(arr));
			echartDataVo.add(echartData);
			types.add(dict.getLabel());
		}
		ActivityEchartVo echartVo = new ActivityEchartVo();
		echartVo.setEchartDataVo(echartDataVo);
		echartVo.setTypes(types);
		echartVo.setYears(years);
		return echartVo;
	}
	// 比如  所有年份为 2010，2011，2012，2013 ，而外出调研的年份只有2010，2013，那么2011，2012就要为0
	private int yearsCompare(int num, List<String> years, ActivityEchartDto activityEchartDto, List<Integer> data) {
		//首先2010比对上了， 2013比对不上， 所有年份中 2011 插入0 
		data.add(0);
		//获取所有年份list的下一条数据接着进行比较  ， list指List<String> years
		num ++;
		//就是2012 进行比较
		if(StringUtils.equals(years.get(num), activityEchartDto.getYears())) {
			data.add(activityEchartDto.getTotal());
			num ++;
			
		}else {
			//2012比较不相同，然后回调此方法， 同时 2012年的为0，获取list下一个年份，就是2013年  ，比较成功就不回调此方法了
			yearsCompare(num,years,activityEchartDto,data);
		}
		//此时发现2011，2012都已经设置为data中数据为0了， 如果list中还有2014，2015 ，那么num++ 就可以定位到 此数据的位置
		return num;
	}

	
	
}